// Global variables
// IE4+, Mozilla only
var isCSS = false, isW3C = false, isIE4 = false, isNN4 = false, isIE6CSS = false; isOpera6 = false;
var ctrack = 0, cday, oldcolor, lo, nnwindow = null, loadint;
var images = new Array();
var prevsrc;
var hilightcolor = "#faa943";
var currentHidden = null;
var editable = false;
var old_keydown_event;
var mode;

// Initialize upon load to let all browsers establish content objects
function initDHTMLAPI( ) {
    if (document.images) {
        isCSS = (document.body && document.body.style) ? true : false;
        isW3C = (isCSS && document.getElementById) ? true : false;
        isIE4 = (isCSS && document.all) ? true : false;
        isNN4 = (document.layers) ? true : false;
        isIE6CSS = (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? 
            true : false;

    }
   // opera6 equals to NN4
   if ((navigator.userAgent.indexOf("Opera 6")!=-1) || (navigator.userAgent.indexOf("Opera/6")!=-1))  {
      isOpera6 = true;
   }
   // cache images
   images[0] = new Image(); images[0].src = "../img/comment_being_edited.gif";
   images[1] = new Image(); images[1].src = "../img/comment_blank.gif";
   images[2] = new Image(); images[2].src = "../img/comment_entered.gif";
   //confirm(isNN4);
}

// Set the visibility of an object to visible
function show(obj) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.visibility = "visible";
    }
}
   
// Set the visibility of an object to hidden
function hide(obj) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.visibility = "hidden";
    }
}

function getElementPosition(offsetTrail) {
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

// Convert object name string or object reference
// into a valid element object reference
function getRawObject(obj) {
    var theObj;       
    if (typeof obj == "string") {
        if (isW3C) {
            theObj = document.getElementById(obj);
        } else if (isIE4) {
            theObj = document.all(obj);
        }
    } else {
        // pass through object reference
        theObj = obj;
    }
    return theObj;
}
   
// Convert object name string or object reference
// into a valid style (or NN4 layer) reference
function getObject(obj) {
    var theObj = getRawObject(obj);
    if (theObj && isCSS) {
        theObj = theObj.style;
    }
    return theObj;
}

// Position an object at a specific pixel coordinate
function shiftTo(obj, x, y) {
    var theObj = getObject(obj);
    if (theObj) {
        if (isCSS) {
            // equalize incorrect numeric value type
            var units = (typeof theObj.left == "string") ? "px" : 0;
            theObj.left = x + units;
            theObj.top = y + units;
        } else if (isNN4) {
            theObj.moveTo(x,y);
        }
    }
}

function findCommentHidden(name) {
    return document.SubmitTTForm.elements[name];
}

function hiLight(id) {
        var theObj = getObject(id);
        if (isNN4) {
            oldcolor = theObj.bgColor;
            lo = theObj;
            theObj.bgColor = hilightcolor;
        } else if (isCSS) {
            oldcolor = theObj.borderColor;
            lo = theObj;
            theObj.backgroundColor=hilightcolor;
        }

}

function loLight() {
        if (isNN4) {
            lo.bgColor = oldcolor;
        } else if (isCSS) {
            lo.backgroundColor = oldcolor;
        }
}

// Return the available content height space in browser window
function getInsideWindowHeight( ) {
    if (window.innerHeight) {
        return window.innerHeight;
    } else if (isIE6CSS) {
        // measure the html element's clientHeight
        return document.body.parentElement.clientHeight;
    } else if (document.body && document.body.clientHeight) {
        return document.body.clientHeight;
    }
    return 0;
}

// Return the available content width space in browser window
function getInsideWindowWidth( ) {
    if (window.innerWidth) {
        return window.innerWidth;
    } else if (isIE6CSS) {
        // measure the html element's clientWidth
        return document.body.parentElement.clientWidth;
    } else if (document.body && document.body.clientWidth) {
        return document.body.clientWidth;
    }
    return 0;
}

// Retrieve the rendered width of an element
function getObjectWidth(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetWidth) {
        result = elem.offsetWidth;
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}

// Retrieve the rendered height of an element
function getObjectHeight(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}

// return client size 
function getClientSize() {
    // window scroll factors
    var scrollX = 0, scrollY = 0;
    if (document.body && typeof document.body.scrollTop != "undefined") {
        scrollX += document.body.scrollLeft;
        scrollY += document.body.scrollTop;
        if (document.body.parentNode && 
            typeof document.body.parentNode.scrollTop != "undefined") {
            scrollX += document.body.parentNode.scrollLeft;
            scrollY += document.body.parentNode.scrollTop;
        }
    } else if (typeof window.pageXOffset != "undefined") {
        scrollX += window.pageXOffset;
        scrollY += window.pageYOffset;
    }
    return new Array(getInsideWindowWidth() + scrollX, getInsideWindowHeight() + scrollY);
}

function DebugObj(obj) {
  var s = "";
  for(var i in obj) {
    s += obj + "." + i + "=" + obj[i] + "; ";
  }
  confirm(s);
}


function openNN_EditCommentsWindow(ct, cd, URL) {
  if(nnwindow && !nnwindow.closed)
        nnwindow.focus();
  else {
      editable = true;
      nnwindow = popup(URL, "popupEditComment", 420, 300, true, true, true);
  }
}

function openNN_ViewCommentsWindow(ct, cd, URL) {
  if(nnwindow && !nnwindow.closed)
        nnwindow.focus();
  else {
      editable = false;
      nnwindow = popup(URL, "popupViewComment", 420, 250, false, false, true);
  }
}

function validateModifications()
{
   if(ctrack != 0 && currentHidden) {
      if(trim(currentHidden.value).replace(/\r/g, "") != trim(document.savecom.comment.value).replace(/\r/g, ""))
        if(!confirm("Modifications made in the comments will be lost. Are you sure you want to continue?"))
          return false;
   }
   return true;
}

function editCommentWindow(link, ct, cd, commentHidden, URL) {
  if(!(isCSS && isW3C && isIE4 && isNN4 && isIE6CSS && isOpera6))
    initDHTMLAPI();

  if(isNN4 || isOpera6) {
    // open a new window for NN4
     openNN_EditCommentsWindow(ct, cd, URL);
     return false;
  }

  if(ctrack == ct && cday == cd)
    return;

  // window is opened, check if user modified something
  if(ctrack != 0) {
     if(mode == "view")
        HideViewWindow();
     else
        if(validateModifications())
            performHideEditWindow();
        else
            return;
  }

  var f = document.savecom.comment;
  currentHidden = findCommentHidden(commentHidden);
  if(currentHidden == null) return;
  f.value = currentHidden.value;
  ctrack = ct; cday = cd;
  var cs = getClientSize('editDiv');
  var osx = getObjectWidth('editDiv');
  var osy = getObjectHeight('editDiv');
  var pos = getElementPosition(link);  
  var newX = 0;
  var newY = pos.top + 30;


    if(isIE4)  {
      var deltaX = cs[0] - pos.left - 10 - osx;
      var deltaY = cs[1] - pos.top - 20 - osy;
      if(deltaX < 0) {
        newX = pos.left + deltaX;
      }
      else
        {
          newX = pos.left - 60;
        }
      if(deltaY < 0) {
        // check if we can safely move the div on top of the image
        if(pos.top > osy) {
          // do the move
          newY = pos.top - osy;
        }
      }
    }
    else  {
      var deltaX = cs[0] - pos.left - osx - 25;
      var deltaY = cs[1] - pos.top - 20 - osy;
      if(deltaX < 0) {
        newX = pos.left - 14 + deltaX;
      }
      else
        {
          newX = pos.left - 60;
        }
      if(deltaY < 0) {
        // check if we can safely move the div on top of the image
        if(pos.top > osy) {
          // do the move
          newY = pos.top - osy - 30;
        }
      }
    }

  shiftTo('editDiv', newX, newY);
  old_keydown_event = document.onkeydown;
  document.onkeydown = keyPressed;
  //document.onkeyup = keyPressed;
  mode = "edit";
  show('editDiv');
  hiLight("timeTrack[" + ctrack + "].obj[" + cday + "]");
  setImage(0);
  document.savecom.comment.focus();
  return false;
}

function keyPressed(evt) {
  if(isIE4)     {
    if(event.keyCode == 27) {
      //event.cancelBubble = true;
      event.returnValue = false;
      HideWindow();
      return false;
    }
  }
  else {
    if(evt.keyCode == 27) {
      evt.preventDefault();
      HideWindow();
      return false;
    }
  }
}

function viewCommentWindow(link, ct, cd, commentHidden, URL) {
  if(!(isCSS && isW3C && isIE4 && isNN4 && isIE6CSS && isOpera6))
    initDHTMLAPI();

  if(isNN4 || isOpera6) {
    // open a new window for NN4
     openNN_ViewCommentsWindow(ct, cd, URL);
     return false;
  }

  if(ctrack == ct && cday == cd)
    return;

  if(ctrack != 0) {
     if(mode == "view")
        HideViewWindow();
     else
        if(validateModifications())
            performHideEditWindow();
        else
            return;
  }

  currentHidden = findCommentHidden(commentHidden);
  if(currentHidden == null) return;
  var f = document.savecom.comment;
  f.value = currentHidden.value;
  ctrack = ct; cday = cd;
  var cs = getClientSize('editDiv');
  var osx = getObjectWidth('editDiv');
  var osy = getObjectHeight('editDiv');
  var pos = getElementPosition(link);  
  var newX = 0;
  var newY = pos.top + 30;


    if(isIE4)  {
      var deltaX = cs[0] - pos.left - 10 - osx;
      var deltaY = cs[1] - pos.top - 20 - osy;

      if(deltaX < 0) {
        newX = pos.left + deltaX;
      }
      else
        {
          newX = pos.left - 60;
        }
      if(deltaY < 0) {
        // check if we can safely move the div on top of the image
        if(pos.top > osy) {
          // do the move
          newY = pos.top - (osy / 2);
        }
      }
    }
    else  {
      var deltaX = cs[0] - pos.left - osx - 25;
      var deltaY = cs[1] - pos.top - 20 - osy;
      if(deltaX < 0) {
        newX = pos.left - 14 + deltaX;
      }
      else
        {
          newX = pos.left - 60;
        }
      if(deltaY < 0) {
        // check if we can safely move the div on top of the image
        if(pos.top > osy) {
          // do the move
          newY = pos.top - (osy / 2);
        }
      }
    }

  shiftTo('infoDiv', newX, newY);
  mode = "view";
  show('infoDiv');
  hiLight("timeTrack[" + ctrack + "].obj[" + cday + "]");
  old_keydown_event = document.onkeydown;
  document.onkeydown = keyPressed;
  var sp = document.getElementById('infoText');
  sp.innerHTML = currentHidden.value.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<br>");
  return false;
}

function setImage(imageNum) {
      f = document.images["timeTrack[" + ctrack + "].commentImg[" + cday + "]"];
      if(f) {
             for(var i = 0; i < images.length; i++) {
               if(images[i].src.toLowerCase() == f.src.toLowerCase()) {
                 prevsrc = i; break;
               }
             }
             f.src = images[imageNum].src;
      }
}

function HideWindow() {
    if(mode == "edit")
        HideEditWindow();
    else
        HideViewWindow();
}

function performHideEditWindow()
{
  hide('editDiv');
  setImage(prevsrc);
  selectSpentStr();
  loLight();
  ctrack = 0;
  cday = 0;
  document.onkeydown = old_keydown_event;
}

function HideEditWindow() {
  if(trim(currentHidden.value).replace(/\r/g, "") != trim(document.savecom.comment.value).replace(/\r/g, "")) {
    if(!confirm("Modifications made in the comments will be lost. Are you sure you want to continue?")) {
      return;
    }
  }
  performHideEditWindow();
  return false;
}

function HideViewWindow() {
  hide('infoDiv');
  loLight();
  ctrack = 0;
  cday = 0;
  return false;
}

function selectSpentStr() {
   el = document.SubmitTTForm.elements["timeTrack[" + ctrack + "].spentStr[" + cday + "]"];
   if(el)
      el.focus();
}

function SaveComment() {
  var ta = trim(document.savecom.comment.value);
  if(ta.length <= 2000) {
     if(ta != currentHidden.value) {
         currentHidden.value = ta;
     }
     if(ta.length == 0) setImage(1)
       else setImage(2);
     selectSpentStr();
     ctrack = cday = 0;
     hide('editDiv');
     loLight();
     window.onkeydown = old_keydown_event;
     if(currentHidden.value != currentHidden.defaultValue || (!isIE4)) {
         if(!dataModified[currentHidden.name])
                dataModified[currentHidden.name] = currentHidden;
    } else {
         if(dataModified[currentHidden.name])
            delete dataModified[currentHidden.name];
    }
  } else
       alert("Comments are too long.\n\nMaximum comments length is 2000 characters.\nCurrent comments length is " + ta.length + " characters.\nPlease shorten the comments.");
}

function commentsPresent(taskId) {
    var f = document.SubmitTTForm;
    for(var i = 0; i < 7; i++) {
        s = "timeTrack[" + taskId + "].comment[" + i + "]";
        if(f.elements[s] && f.elements[s].value != "")
               return true;
    }
    return false;
}